/**
 * Copyright (C), 2019-2023, lepus-dt.comInc. All rights reserved.
 * FileName: I18nMessage
 * Author:   chao.xie
 * Date:     2023.06.06
 */
package org.jeecg.extra.utils;

import cn.hutool.core.util.StrUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * 国际化工具<br/><br/>
 *
 * <p>通过SpringBoot方式获取消息.
 *
 * @author chao.xie
 * @version 1.0.0
 * @创建日期: 2024.03.15
 */
public class I18nUtils {
    private static final String HEADER_PARAM_LANGUAGE = "X-Language";

    /**
     * 获取多语言支持
     *
     * @param key 关键字
     * @return
     */
    public static String getMessage(String key) {
        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
        RequestContext requestContext = new RequestContext(request);

        String language = request.getHeader(HEADER_PARAM_LANGUAGE);
        Locale locale;
        try {
            if (StrUtil.isNotEmpty(language)) {
                //按照指定的正则表达式，解析出相关的数据信息
                String[] split = language.split(StrUtil.DASHED);
                //解析出数据后，修改local对象
                locale = new Locale(split[0], split[1]);
            } else {
                locale = Locale.CHINA;
            }
        } catch (Exception ex) {
            locale = Locale.CHINA;
        }

        requestContext.changeLocale(locale);

        String message = "";
        try {
            message = requestContext.getMessage(key);
        } catch (Exception exception) {
            message = key;
        }

        return message;
    }

    public static String getMessage(String key, Object... args) {
        String message = getMessage(key);
        return StrUtil.format(message, args);
    }
}
